<template>
  <div class="app-container">
    <div class="Search">
      <!--工具条-->
      <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
        <el-form :inline="true" :model="query">
          <el-form-item v-has="'PLATFROM_TENANT_QUERY'">
            <el-cascader ref="tenantTree" placeholder="所属租户" :props="tenantProps" :options="tenantOptions" @change="selectTenant" clearable collapse-tags filterable></el-cascader>
          </el-form-item>
          <el-form-item>
            <el-cascader ref="organTree" placeholder="所属组织" :props="props" :options="organOptions" @change="selectOrgan" clearable collapse-tags filterable></el-cascader>
          </el-form-item>
          <el-form-item>
            <el-input v-model="query.params.userName" placeholder="用户名" clearable auto-complete="off" />
          </el-form-item>
          <el-form-item>
            <el-select v-model="query.params.enable" clearable placeholder="是否生效">
              <el-option v-for="item in query.enableOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select v-model="query.params.isAccountNonExpired" clearable placeholder="是否账号过期">
              <el-option v-for="item in query.isAccountNonExpiredOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button v-has="'USER_INDEX'" type="primary" icon="el-icon-search" size="mini" @click="fetchData">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button v-has="'USER_EDIT'" type="success" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </div>
    <div class="block">
      <el-table v-loading="listLoading" :data="list" element-loading-text="Loading" border fit highlight-current-row>
        <el-table-column align="center" label="序号" width="95">
          <template slot-scope="scope">
            {{ scope.$index }}
          </template>
        </el-table-column>
        <el-table-column label="所属机构" width="110">
          <template slot-scope="scope">
            {{ scope.row.organName }}
          </template>
        </el-table-column>
        <el-table-column label="用户名" width="110">
          <template slot-scope="scope">
            {{ scope.row.userName }}
          </template>
        </el-table-column>
        <el-table-column label="是否生效" width="110" prop="enable" :formatter="enableFormat" />
        <el-table-column label="是否账号过期" width="110" prop="isAccountNonExpired" :formatter="isAccountNonExpired" />
        <el-table-column label="是否锁定" width="110" prop="isLock" :formatter="isLock" />
        <el-table-column label="是否超管" width="110" prop="isSuperMgr" :formatter="isSuperMgr" />
        <el-table-column label="备注" width="110">
          <template slot-scope="scope">
            {{ scope.row.remark }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" align="center" prop="created_at" label="操作">
          <template slot-scope="scope">
            <el-link v-has="'USER_EDIT'" type="warning" icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)">修改</el-link>
            <el-link v-if="true" v-has="'USER_REMOVE'" class="el-icon-delete" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-link>
            <el-link v-has="'USER_ROLE_GET_ROLES_AND_ASSIGN'" class="el-icon-s-custom" type="success" @click="assignRoles(scope.$index, scope.row)">分配角色</el-link>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="block">
      <el-pagination :current-page="currentPage" :page-sizes="[10, 20, 30, 40]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
    <div class="block">
      <!--弹框-->
      <el-dialog :title="titleMap[dialogStatus]" :visible.sync="dialogFormVisible">
        <el-form :model="form" :rules="userRules" ref="userForm">
          <el-form-item v-if="addForVisible" label="用户编号">
            <el-input v-model="form.id" disabled placeholder="编号" auto-complete="off" />
          </el-form-item>
          <el-form-item v-has="'PLATFROM_TENANT_QUERY'" label="所属租户" placeholder="所属租户" required>
            <el-cascader v-model="form.tenantId" ref="tenantTreeForm" placeholder="所属租户" :props="tenantProps" :options="tenantOptions" @change="chooseTenantForm" style="width:100%" clearable collapse-tags filterable></el-cascader>
          </el-form-item>
          <el-form-item label="所属组织">
            <el-cascader v-model="form.organId" ref="organTreeForm" placeholder="所属组织" :props="props" :options="organFormOptions" @change="chooseOrganForm" style="width:100%" collapse-tags filterable></el-cascader>
          </el-form-item>
          <el-form-item label="用户名" placeholder="用户名" prop="userName" required>
            <el-input v-model="form.userName" clearable auto-complete="off" />
          </el-form-item>
          <el-form-item label="密码" placeholder="密码" prop="password" required>
            <el-input :type="'password'" v-model="form.password" show-password clearable auto-complete="off" />
          </el-form-item>
          <el-form-item label="是否生效">
            <el-select v-model="form.enable" clearable placeholder="是否生效" style="width:100%">
              <el-option v-for="item in query.enableOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="是否账号过期">
            <el-select v-model="form.isAccountNonExpired" clearable placeholder="是否账号过期" style="width:100%">
              <el-option v-for="item in query.isAccountNonExpiredOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="是否锁定">
            <el-select v-model="form.isLock" clearable placeholder="是否锁定" style="width:100%">
              <el-option v-for="item in query.isLockOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="是否超管">
            <el-select v-model="form.isSuperMgr" clearable placeholder="是否超管" style="width:100%">
              <el-option v-for="item in query.isSuperMgrOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="form.remark" clearable auto-complete="off" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleEditSave('userForm')">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <div class="block">
      <!--弹框-->
      <el-dialog :title="titleMap[dialogStatus]" :visible.sync="dialogFormAssignRoleVisible">
        <el-form :inline="true" :model="role">
          <el-form-item v-if="false">
            <el-input v-model="form.id" placeholder="角色名称" />
          </el-form-item>
          <el-form-item v-has="'PLATFROM_TENANT_QUERY'" label="所属租户" placeholder="所属租户" required>
            <el-cascader v-model="form.tenantId" ref="tenantTreeForm" placeholder="所属租户" :props="tenantProps" :options="tenantOptions" @change="chooseTenantForm" style="width:100%" clearable collapse-tags filterable></el-cascader>
          </el-form-item>
          <el-form-item label="所属组织" placeholder="所属组织" required>
            <el-cascader v-model="form.organId" ref="organTreeForm" placeholder="所属组织" :props="props" :options="organFormOptions" @change="chooseOrganForm" style="width:100%" collapse-tags filterable clearable></el-cascader>
          </el-form-item>
        </el-form>
        <el-table ref="roleSelectionTable" v-loading="listLoading" :data="roleList" element-loading-text="Loading" border fit highlight-current-row @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column label="角色名称" width="110">
            <template slot-scope="scope">
              {{ scope.row.roleName }}
            </template>
          </el-table-column>
          <el-table-column label="角色代码" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.code }}</span>
            </template>
          </el-table-column>
          <el-table-column label="类型" width="110" align="center" prop="type" :formatter="typeFormater" />
          <el-table-column label="所属组织" width="110" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.organName }}</span>
            </template>
          </el-table-column>
        </el-table>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormAssignRoleVisible = false">取 消</el-button>
          <el-button type="primary" @click="getRoleSelectionAndSave">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { getList, doDelete, doEdit } from '@/api/User/'
import { querySubordinateOrgan } from '@/api/Organ'
import { getDictionaryGroup } from '@/api/dictionary'
import { getRolesAndAssigned, assigningOrRemoveRole, modifyUserRole, getAssigned2OrganForAssigning2User } from '@/api/role'
import { getOrganId, getTenantId, getOrganPath, getCurrentLoginUserId, handleBuildTreeDataStruct, getSelectedNodes, getSelectedNodesObject, getSystemErrorCode } from '@/api/utils'
import { getTenantList, getOrganList, getDictionary, translateOrganId2OrganName } from '@/utils/auth'

import localStorageUtil from '@/utils/localStorageUtil'


export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(status) {
      const typeMap = {
        '1': '超级管理员',
        '2': '管理员',
        '3': '普通用户'
      }
      const typeDesc = typeMap[status]
      return typeDesc
    }
  },
  data() {
    return {
      list: [],
      listLoading: true,
      roleLoading: true,
      total: 5,
      currentPage: 1,
      pageSize: 10,
      dialogFormVisible: false,
      dialogFormAssignRoleVisible: false,
      addForVisible: false,
      visableFilter: {},
      isClearable: true, // 可清空（可选）
      isAccordion: true, // 可收起（可选）
      valueId: {}, // 初始ID（可选）
      defaultSelectedNodes: [],
      form: {
        id: '',
        enable: '1',
        isAccountNonExpired: '0',
        isLock: '0',
        isSuperMgr: '0',
        organId: '',
        organPath: '',
        password: '',
        remark: '',
        updateBy: '',
        updateDate: '',
        userName: ''
      },
      userRules: {
        userName: [{ required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 6, max: 128, message: '长度在 6 到 128 个字符', trigger: 'blur' }
        ],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 18, message: '长度在 8 到 18 个字符', trigger: 'blur' }
        ]
      },
      // 新增or编辑弹框标题(根据点击的新增or编辑按钮显示不同的标题)
      titleMap: {
        add: '新增用户',
        edit: '编辑用户',
        assign: '分配角色'
      },
      props: { // 配置项（必选）
        value: 'id',
        label: 'organName',
        children: 'children',
        title: '组织',
        multiple: false,
        checkStrictly: true,
        emitPath: false
        // disabled:true
      },
      organOptions: [{ id: '1', parentId: '2', organName: '平台', children: [] }],
      tenantProps: { // 配置项（必选）
        value: 'id',
        label: 'organName',
        children: 'children',
        title: '租户',
        multiple: false,
        checkStrictly: true,
        emitPath: false
        // disabled:true
      },
      organFormOptions: [],
      tenantOptions: [],
      // 新增和编辑弹框标题
      dialogStatus: '',
      query: {
        params: {
          enable: '', // 角色名称
          isAccountNonExpired: '',
          isLock: '',
          isSuperMgr: '',
          organId: '',
          organPath: '',
          password: '',
          remark: '',
          updateBy: '',
          updateDate: '',
          tenantId: '',
          userName: ''
        },
        timeValue: '',
        roleTypeOptions: [],
        enableOptions: [{
          value: '0',
          label: '失效'
        }, {
          value: '1',
          label: '生效'
        }],
        isAccountNonExpiredOptions: [{
          value: '0',
          label: '未过期'
        }, {
          value: '1',
          label: '过期'
        }],
        isLockOptions: [{
          value: '0',
          label: '未锁定'
        }, {
          value: '1',
          label: '锁定'
        }],
        isSuperMgrOptions: [{
          value: '0',
          label: '否'
        }, {
          value: '1',
          label: '是'
        }],
        value: ''
      },
      role: {
        pageSize: 20,
        currentPage: 1,
        total: 0,
        userId: '',
        selected: [],
        selectedAll: {}
      },
      organ: {
        id: ''
      },
      roleList: [],
      roleSelection: [],
      defaultProps: {
        children: 'children',
        label: 'name',
        url: 'url'
      }

    }
  },
  created() {

    this.initOrganTree(() => {
      this.setOrganQueryType()
    }, getOrganPath())
    this.initOrganFormTree()
    this.handleFiltTenant()
    this.handleBuildLockOptions()
    this.handleBuildAccountNonExpiredOptions()
    this.hadnleBuildSuperMgrOptions()
    this.handleBuildEnableOptions()
    this.handleBuildRoleTypeOptions()
    this.fetchData()
  },
  methods: {
    isAccountNonExpired(row, column) {
      let label = ''
      for (let i = 0; i < this.query.isAccountNonExpiredOptions.length; i++) {
        if ('' + row.isLock === this.query.isAccountNonExpiredOptions[i].value) {
          return this.query.isAccountNonExpiredOptions[i].label
        }

      }
      return label

    },
    isLock(row, column) {
      let label = ''
      for (let i = 0; i < this.query.isLockOptions.length; i++) {
        if ('' + row.isLock === this.query.isLockOptions[i].value) {
          return this.query.isLockOptions[i].label
        }

      }
      return label

    },
    isSuperMgr(row, column) {
      let label = ''
      for (let i = 0; i < this.query.isSuperMgrOptions.length; i++) {
        if ('' + row.isLock === this.query.isSuperMgrOptions[i].value) {
          return this.query.isSuperMgrOptions[i].label
        }
      }
      return label
    },
    enableFormat(row, column) {

      let label = ''
      for (let i = 0; i < this.query.enableOptions.length; i++) {
        if ('' + row.enable === this.query.enableOptions[i].value) {
          return this.query.enableOptions[i].label
        }
      }
      return label
    },
    typeFormater(row, column) {
      let label = ''
      for (let i = 0; i < this.query.roleTypeOptions.length; i++) {
        if ('' + row.type === this.query.roleTypeOptions[i].value) {
          return this.query.roleTypeOptions[i].label
        }

      }
      return label
    },
    fetchData() {
      this.listLoading = true
      // 数据权限
      this.createOrganQuery()
      this.currentPage = this.currentPage || 1
      this.pageSize = this.pageSize || 10
      getList(this.query.params, this.currentPage, this.pageSize).then(response => {
        let data = response.data
        if (!data.entities || typeof data.successful != 'undefined') {
          this.$message({
            type: 'info',
            message: data.description || getSystemErrorCode(data.status)
          })
        }
        this.total = data.totalCount
        this.pageSize = data.pageSize
        this.currentPage = data.currentPage
        this.list = data.entities
        this.listLoading = false
      })
    },
    createOrganQuery() {
      // 选中了租户
      let tenantSelected = this.$refs['tenantTree'] && this.$refs['tenantTree'].getCheckedNodes() || []
      let organSelected = this.$refs['organTree'] && this.$refs['organTree'].getCheckedNodes() || []
      let that = this
      this.query.params.organId = null
      if (tenantSelected.length && tenantSelected[0]) {
        this.query.params.tenantId = tenantSelected[0].data.id
        if (organSelected.length && organSelected[0]) {
          if (this.props.multiple) {
            this.query.params.organId = null
            this.query.params.organIds = []
            if (organSelected.length && organSelected[0]) {
              organSelected.forEach(function (element) {
                that.query.params.organIds.push(element.data.id)
              })
            }
          } else if (organSelected.length && organSelected[0]) {
            this.query.params.organPath = organSelected[0] && organSelected[0].data.organPath
          }
        }
      } else {
        this.query.params.tenantId = getTenantId()
        if (organSelected.length && organSelected[0]) {
          if (this.props.multiple) {
            this.query.params.organId = null
            this.query.params.organIds = []
            if (organSelected.length && organSelected[0]) {
              organSelected.forEach(function (element) {
                that.query.params.organIds.push(element.data.id)
              })
            }
          } else if (organSelected.length && organSelected[0]) {
            this.query.params.organPath = organSelected[0].data.organPath
          }
        }

      }
      this.query.params.organId = this.query.params.organId || getOrganId()
      this.query.params.organPath = this.query.params.organPath || getOrganPath()
    },

    fetchRoleData(tenantId, organId, userId) {
      this.roleLoading = true
      getAssigned2OrganForAssigning2User({ "tenantId": tenantId, "organId": organId, "userId": userId }).then(response => {
        let gateway = response.data
        this.roleList = gateway.data

        if (gateway.successful) {
          let assignedRoles = getSelectedNodesObject(this.roleList, 'hasRole')
          this.$nextTick(function() {
            assignedRoles.forEach(row => {
              this.$refs.roleSelectionTable.toggleRowSelection(row);
            })
          })
        } else {
          this.$message({
            type: 'info',
            message: getSystemErrorCode(gateway.status)
          })
        }

        this.roleLoading = false
      })
    },
    handleFiltTenant() {
      let data = getOrganList()
      this.tenantOptions = data.filter(function(item, index) {
        return item.type == 0 || item.type == 1;
      })
    },
    handleSizeChange(val) {
      this.currentPage = 1
      this.pageSize = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchData()
    },
    // 新增
    handleAdd() {
      let that = this
      this.initOrganFormTree(function() {
        // 显示弹框
        that.dialogFormVisible = true
      })
      // 新增弹框标题
      this.dialogStatus = 'add'
      this.form.enable = ''
      this.form.id = ''
      this.form.isAccountNonExpired = ''
      this.form.isLock = ''
      this.form.isSuperMgr = ''
      this.form.isAccountNonExpired = '0'
      this.form.isLock = '0'
      this.form.isSuperMgr = '0'
      this.form.enable = '1'
      this.form.organId = ''
      this.form.organPath = ''
      this.form.password = ''
      this.form.remark = ''
      this.form.userName = ''
      this.form.createBy = ''
      this.form.createDate = ''
      this.form.updateBy = ''
      this.form.updateDate = ''
      this.form.tenantId = this.form.tenantId || getTenantId()
      this.addForVisible = false
    },
    // 编辑
    handleEdit(index, row) {
      let that = this
      this.initOrganFormTree(function() {
        // 显示弹框
        that.dialogFormVisible = true
      })
      this.form.createBy = row.createBy
      this.form.createDate = row.createDate
      this.form.id = row.id
      this.form.isAccountNonExpired = '' + row.isAccountNonExpired
      this.form.isLock = '' + row.isLock
      this.form.isSuperMgr = '' + row.isSuperMgr
      this.form.enable = '' + row.enable
      this.form.organId = row.organId
      this.form.organPath = row.organPath
      this.form.password = row.password
      this.form.remark = row.remark
      this.form.updateBy = row.updateBy
      this.form.updateDate = row.updateDate
      this.form.userName = row.userName
      this.form.tenantId = row.tenantId
      this.addForVisible = true
      // 编辑弹框标题
      this.dialogStatus = 'edit'
    },
    handleDelete(index, row) {
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        doDelete(row.id).then(response => {
          const data = response.data
          console.log(data)
          if (data.status === 1) {
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
            this.fetchData()
          } else if (data.status === 403) {
            this.$message({
              type: 'warning',
              message: data.description
            })
          } else {
            this.$message({
              type: 'info',
              message: '操作失败!'
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleEditSave(formName) {

      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.form.createBy = getCurrentLoginUserId()
          this.form.updateBy = getCurrentLoginUserId()
          doEdit(this.form).then(response => {
            console.log(response)
            const data = response.data
            if (data.status === 1) {
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
              this.fetchData()
            } else if (data.status === 403) {
              this.$message({
                type: 'warning',
                message: data.description
              })
            } else {
              this.$message({
                type: 'info',
                message: '操作失败!'
              })
            }
            this.listLoading = false
            this.dialogFormVisible = false
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    handleReset() {
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    assignRoles(index, row) {
      this.dialogStatus = 'assign'
      this.dialogFormAssignRoleVisible = true
      this.form.tenantId = row.tenantId
      this.form.organId = row.organId
      this.role.userId = row.id
      this.fetchRoleData(row.tenantId, row.organId, row.id)
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.role.selectedAll[row.id] = row
          this.$refs.multipleTable.toggleRowSelection(row, true)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },
    handleSelectionChange(selection) {
      this.roleSelection = selection
      // console.log(this.selected)
    },
    handleSelect(selection, row) {
      console.log(this.role.selectedAll)
      console.log(selection)
      console.log(selection.length)
      const userRole = {}
      if (selection[selection.length - 1].id === row.id) {
        // 新赋一个角色
        userRole['userId'] = this.role.userId
        userRole['roleId'] = row.id
      } else {
        // 删除一个角色
        // 新赋一个角色
        userRole['userId'] = this.role.userId
        userRole['roleId'] = row.id
        userRole['id'] = row.userRole.id
      }

      if (userRole.id) {
        // 删除角色询问确认一下
        this.$confirm('此操作可能会影响用户的功能使用, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }).then(() => {
          assigningOrRemoveRole(userRole).then(response => {
            const data = response.data
            console.log(response)
            if (data.status === 1) {
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
            } else if (data.status === 403) {
              this.$message({
                type: 'warning',
                message: data.description
              })
            } else {
              this.$message({
                type: 'info',
                message: '操作失败!'
              })
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          })
        })
      } else {
        // 分配角色不用询问
        assigningOrRemoveRole(userRole).then(response => {
          const data = response.data
          console.log(response)
          if (data.status === 1) {
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
          } else if (data.status === 403) {
            this.$message({
              type: 'warning',
              message: data.description
            })
          } else {
            this.$message({
              type: 'info',
              message: '操作失败!'
            })
          }
        })
      }
    },
    handleBuildLockOptions() {

      const datas = getDictionary()
      let data = datas.filter(function(item, index) {
        return item.bigType === "UserLock" && item.parentId != '0';
      })
      let isLockOptions = [];
      for (let i = 0; i < data.length; i++) {

        let option = {}
        option['value'] = data[i].value
        option['label'] = data[i].desc
        isLockOptions.push(option)
      }
      this.query.isLockOptions = isLockOptions
    },
    handleBuildAccountNonExpiredOptions() {

      const datas = getDictionary()
      let data = datas.filter(function(item, index) {
        return item.bigType === "UserExpire" && item.parentId != '0';
      })
      let isAccountNonExpiredOptions = [];
      for (let i = 0; i < data.length; i++) {

        let option = {}
        option['value'] = data[i].value
        option['label'] = data[i].desc
        isAccountNonExpiredOptions.push(option)
      }
      this.query.isAccountNonExpiredOptions = isAccountNonExpiredOptions
    },
    hadnleBuildSuperMgrOptions() {

      const datas = getDictionary()
      let data = datas.filter(function(item, index) {
        return item.bigType === "UserSuperManager" && item.parentId != '0';
      })
      let isSuperMgrOptions = [];
      for (let i = 0; i < data.length; i++) {

        let option = {}
        option['value'] = data[i].value
        option['label'] = data[i].desc
        isSuperMgrOptions.push(option)
      }
      this.query.isSuperMgrOptions = isSuperMgrOptions
    },
    handleBuildEnableOptions() {

      const datas = getDictionary()
      let data = datas.filter(function(item, index) {
        return item.bigType === "UserEnable" && item.parentId != '0';
      })
      let enableOptions = [];
      for (let i = 0; i < data.length; i++) {

        let option = {}
        option['value'] = data[i].value
        option['label'] = data[i].desc
        enableOptions.push(option)
      }
      this.query.enableOptions = enableOptions
    },
    handleBuildRoleTypeOptions() {

      const datas = getDictionary()
      let data = datas.filter(function(item, index) {
        return item.bigType === "UserRole" && item.parentId != '0';
      })
      let roleTypeOptions = [];
      for (let i = 0; i < data.length; i++) {

        let option = {}
        option['value'] = data[i].value
        option['label'] = data[i].desc
        roleTypeOptions.push(option)
      }
      this.query.roleTypeOptions = roleTypeOptions
    },

    handleSelected() {

    },
    getValue(value) {
      this.valueId = value
      this.query.params.organPath = value.organPath
      console.log(this.valueId)
    },
    getRoleSelectionAndSave() {

      const batchModify = []
      for (let i = 0; i < this.roleSelection.length; i++) {

        const userRole = {}
        if (this.roleSelection[i].userRoleId) {
          userRole['id'] = this.roleSelection[i].userRoleId
        }
        userRole['userId'] = this.role.userId
        userRole['roleId'] = this.roleSelection[i].id
        if (this.form.tenantId) {
          userRole['tenantId'] = this.form.tenantId
        } else {
          userRole['tenantId'] = getTenantId()
        }
        if (this.form.organId) {
          userRole['organId'] = this.form.organId
        } else {
          userRole['organId'] = this.roleSelection[i].organId
        }
        batchModify.push(userRole)
      }

      modifyUserRole({ userId: this.role.userId, organId: this.organ.id }, batchModify)
        .then(response => {
          console.log(response)
          const data = response.data
          if (data.status < 200 && data.status >= 1) {
            this.$message({
              type: 'success',
              message: '操作成功!'
            })

            this.dialogFormAssignRoleVisible = false
          } else if (data.status === 403) {
            this.$message({
              type: 'warning',
              message: data.description
            })
          } else {
            this.$message({
              type: 'info',
              message: '操作失败!'
            })
          }
        })

    },
    getCheckedNodes() {
      const checkedList = this.$refs.tree.getCheckedNodes()
      const halfCheckList = this.$refs.tree.getHalfCheckedNodes()
      const batchModify = []

      const allChecked = []

      for (let i = 0; i < checkedList.length; i++) {
        allChecked.push(checkedList[i])
      }

      for (let i = 0; i < halfCheckList.length; i++) {
        allChecked.push(halfCheckList[i])
      }

      for (let i = 0; i < allChecked.length; i++) {
        const userRole = {}
        if (allChecked[i].userRole && allChecked[i].userRole.id) {
          userRole['id'] = allChecked[i].userRole.id
        }
        userRole['userId'] = this.role.userId
        userRole['roleId'] = allChecked[i].id
        userRole['organId'] = getOrganId()
        batchModify.push(userRole)
      }

      modifyUserRole({ userId: this.role.userId, organId: getOrganId() }, batchModify)
        .then(response => {
          console.log(response)
          const data = response.data
          if (data.status < 200 && data.status >= 1) {
            this.$message({
              type: 'success',
              message: '操作成功!'
            })

            this.dialogFormAssignRoleVisible = false
          } else if (data.status === 403) {
            this.$message({
              type: 'warning',
              message: data.description
            })
          } else {
            this.$message({
              type: 'info',
              message: '操作失败!'
            })
          }
        })
    },
    initOrganTree(fn, filter, that) {
      debugger
      this.listLoading = true
      let data = getOrganList()
      if (filter) {
        data = data.filter(function(item, index) {
          return item.organPath.indexOf(filter) >= 0
        })
      }
      if (that && that.organFormOptions && that.organFormOptions.length === 0) {
        that.organFormOptions = handleBuildTreeDataStruct(data, 'id', 'parentId')
      } else {
        this.organOptions = handleBuildTreeDataStruct(data, 'id', 'parentId')
      }
      this.listLoading = false
      if (fn) {
        fn()
      }
    },
    initOrganFormTree(fn, filter) {
      this.initOrganTree(fn, filter, this)
    },
    setOrganQueryType() {
      this.organQueryModelChange(localStorageUtil.fetch("SYSTEM_SETTING_ORGAN_QUERY_MODEL"))
    },
    selectOrgan(nodes) {
      let nodesInfo = this.$refs['organTree'].getCheckedNodes()
      let that = this
      this.query.params.organPath = ''
      this.query.params.organIds = []
      if (this.props.multiple) {
        this.query.params.organIds = []
        if (nodesInfo.length) {
          nodesInfo.forEach(function(element) {
            that.query.params.organIds.push(element.data.id)
          })
        }
      } else if (nodesInfo.length) {
        this.query.params.organPath = nodesInfo[0].data.organPath
      }
    },
    selectTenant(nodes) {
      debugger
      let nodesInfo = this.$refs['tenantTree'].getCheckedNodes()
      let that = this
      this.query.params.tenantId = ''
      this.query.params.tenantIds = []
      if (this.props.multiple) {
        this.query.params.tenantIds = []
        if (nodesInfo.length) {
          nodesInfo.forEach(function(element) {
            that.query.params.tenantIds.push(element.data.id)
          })
        }
      } else if (nodesInfo.length) {
        this.query.params.tenantId = nodesInfo[0].data.id
        this.initOrganTree(function() {
          that.setOrganQueryType()
        }, nodesInfo[0].data.organPath)
      } else {
        this.initOrganTree(function() {
          that.setOrganQueryType()
        })
      }
    },
    chooseTenantForm(nodes) {
      let that = this
      let nodesInfo = this.$refs['tenantTreeForm'].getCheckedNodes()
      this.form.tenantId = null
      if (nodesInfo.length) {
        this.form.tenantId = nodesInfo[0].data.id
        this.initOrganFormTree(function() {
          that.setOrganQueryType()
        }, nodesInfo[0].data.organPath, this.organFormOptions)
      } else {
        this.initOrganFormTree(function() {
          that.setOrganQueryType()
        }, null, this.organFormOptions)
      }
    },
    organQueryModelChange(organQueryModel) {
      if (organQueryModel == 'selected') {
        this.props.multiple = true
      } else if (organQueryModel == 'selfAndSub') {
        this.props.multiple = false
      }
    },
    chooseOrganForm(nodes) {
      let nodesInfo = this.$refs['organTreeForm'].getCheckedNodes()
      if (nodesInfo[0]) {
        this.form.organPath = nodesInfo[0].data.organPath
        this.form.organId = nodesInfo[0].data.id
        this.form.tenantId = nodesInfo[0].data.tenantId
      }
    },
  }
}

</script>
